package com.devplatform.controller;

import com.devplatform.constants.DataVoCodeConstant;
import com.devplatform.pojo.EmailCode;
import com.devplatform.pojo.vo.DataVo;
import com.devplatform.service.EmailCodeService;
import com.devplatform.util.EmailUtil;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;


@RestController
@RequestMapping("/api/email")
@RequiredArgsConstructor
@Slf4j
public class EmailCodeController {
    private final EmailCodeService emailCodeService;
    private final EmailUtil emailUtil;
    @Value("${mail.intervalTime}")
    private int intervalTime;

    //发送右键验证码
    @GetMapping("/getEmailCode")
    public DataVo<String> getEmailCode(@RequestParam String email, HttpSession session) {
        //验证用户上一次发送验证码时间
        EmailCode emailCode = emailCodeService.getById(session.getId());
        if (emailCode != null) {
            if (emailCode.getSendTime().plusSeconds(intervalTime).isAfter(LocalDateTime.now())) {
                return DataVo.error(DataVoCodeConstant.EMAIL_SEND_FAST, "发送频率过快");
            }
        } else {
            emailCode = new EmailCode();
        }

        String code = emailUtil.sendMail(email);
        if (code == null) return DataVo.error("发送失败");

        //保存至数据库
        emailCode.setSessionId(session.getId());
        emailCode.setEmail(email);
        emailCode.setSendTime(LocalDateTime.now());
        emailCode.setCode(code);
        if (emailCodeService.saveOrUpdate(emailCode)) {
            return DataVo.ok("发送成功");
        } else {
            return DataVo.error("发送失败");
        }
    }
}
